package com.os.opencv.java.chapter12;

import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.TermCriteria;
import org.opencv.highgui.HighGui;
import org.opencv.imgcodecs.Imgcodecs;

public class Kmeans2 {

    public static void main(String[] args) {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        //读取图像并在屏幕上显示
        Mat src = Imgcodecs.imread("pics/face.jpg");
        HighGui.imshow("src", src);
        HighGui.waitKey(0);

        //计算像素数
        int width = src.width();
        int height = src.height();
        int num = width * height;
        Mat pts = new Mat(num, src.channels(), CvType.CV_32F);

        //将图像转换成kmeans函数要求的数据类型
        int index;
        for(int i=0; i<height; i++){
            for(int j=0; j<width; j++){
                index = i * width + j;
                pts.put(index, 0, src.get(i, j)[0]);
                pts.put(index, 1, src.get(i, j)[1]);
                pts.put(index, 2, src.get(i, j)[2]);
            }
        }
        //用k均值算法将像素值分类
        Mat labels = new Mat();
        Mat centers = new Mat(3,3,CvType.CV_32F);
        TermCriteria criteria = new TermCriteria(TermCriteria.COUNT + TermCriteria.EPS, 10, 0.1);
        Core.kmeans(pts, 3, labels, criteria, 3, Core.KMEANS_PP_CENTERS, centers);

        //用于显示结果的图像和颜色
        Mat dst = Mat.zeros(src.size(), src.type());
        double[][] color = {{0,0,255}, {0,255,0}, {255,0,0}};

        //在目标图像上绘制分割结果
        for(int i=0; i<height; i++){
            for(int j=0; j<width; j++){
                index = i * width + j;
                int label = (int)labels.get(index, 0)[0];
                dst.put(i, j, color[label]);
            }
        }

        //在屏幕上显示图像分割结果
        HighGui.imshow("dst", dst);
        HighGui.waitKey(0);
        System.exit(0);
    }
}
